package com.example.springstudyvue.controller;


import com.example.springstudyvue.entity.Area;
import com.example.springstudyvue.mapper.AreaMapper;
import com.example.springstudyvue.result.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author linKe
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/area")
public class AreaController {
    @Resource
    private AreaMapper areaMapper;

    @ApiOperation("区域分级筛选")
    @GetMapping("/tree")
    public Result<List<Area>> findAll() {
        //查询所有区域信息
        List<Area> areas = areaMapper.selectList(null);
        // 第一级  当area的父级id为null是出现在第一级
        List<Area> pNodeList = areas.stream().filter(area -> area.getPid() == null).collect(Collectors.toList());
        for (Area area : pNodeList) {
            //遍历对象得到父级pid 遍历筛选相同的添加到子类元素中
            Integer pid = area.getId();
            // 第二级
            List<Area> secondNodeList = areas.stream().filter(a -> pid.equals(a.getPid())).collect(Collectors.toList());
            area.setChildren(secondNodeList);

            // 第三级  同上
            for (Area secondArea : secondNodeList) {
                Integer secondPid = secondArea.getId();
                List<Area> thirdNodeList = areas.stream().filter(a -> secondPid.equals(a.getPid())).collect(Collectors.toList());
                secondArea.setChildren(thirdNodeList);
            }
        }
        //返回分级后的区域信息
        return Result.data(pNodeList);
    }


}
